package com.yjw.zookeeper.curator_api;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

public class CuratorDemo {

    public static void main(String[] args) {
        // 建立连接
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .connectString("192.168.202.18:2181,192.168.202.49:2181,192.168.202.50:2181")
                .sessionTimeoutMs(4000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .namespace("curator")
                .build();

        curatorFramework.start();

        try {
            // 创建节点
            curatorFramework.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT)
                    .forPath("/node/children1", "0".getBytes());

            // 获取节点
            Stat stat = new Stat();
            byte[] bytes = curatorFramework.getData()
                    .storingStatIn(stat)
                    .forPath("/node/children1");
            System.out.println(new String(bytes));

            // 更新节点
            stat = curatorFramework.setData()
                    .withVersion(stat.getVersion())
                    .forPath("/node/children1", "1".getBytes());

            // 获取节点
            byte[] bytes1 = curatorFramework.getData()
                    .storingStatIn(stat)
                    .forPath("/node/children1");
            System.out.println(new String(bytes1));

            // 删除节点
            curatorFramework.delete()
                    .withVersion(stat.getVersion())
                    .forPath("/node/children1");
        } catch (Exception e) {
            e.printStackTrace();
        }

        curatorFramework.close();
    }
}
